import { Response } from 'express';
import { res_send_cur_identity_card_is_created } from '../Classes/cla_res_send_cur_identity_card_is_created';
import { res_send_cur_phone_is_created } from '../Classes/cla_res_send_cur_phone_is_created';
import { get_db_user_account } from '../../../Func/get_db';
import { user_account_prop_Identity } from '../../../../../Func/sign_info_user_account/Classes/cla_mdb_info_user_account';

type typ_identity_or_phone = {
  Identity: string;
  phone: string;
};

const check_func_arr = {
  Identity: check_is_created_identity,
  phone: check_is_created_phone,
};

type typ_check_func_arr_key = keyof typeof check_func_arr;

const db_user_account_identify = get_db_user_account();

/**
 * 检测 当前数据库 已注册 返回 true
 * @param check_prop_obj 用户 身份证卡号 和 手机号 等 信息
 * @param res response 服务器 响应
 * @returns
 */
export async function check_identity_or_phone_is_created(
  check_prop_obj: typ_identity_or_phone,
  res?: Response | undefined
) {
  let key: typ_check_func_arr_key;
  for (key in check_func_arr) {
    const check_cur_func = check_func_arr[key];

    /**
     * 检测 唯一性 数据 是否 已经注册
     */
    let is_created = await check_cur_func(check_prop_obj[key], res);

    if (is_created) {
      return true;
    }
  }

  return false;
}

async function check_is_created_identity(
  Identity: string,

  res?: Response | undefined
) {
  // 查找 身份证卡号 是否已 注册过
  let had_cur_identity = await db_user_account_identify
    .find({
      [user_account_prop_Identity]: Identity,
    })
    .toArray();

  // 当前 身份证卡号 已 注册
  if (had_cur_identity.length > 0) {
    let cur_identify_is_created = new res_send_cur_identity_card_is_created(
      Identity
    );
    res?.send(cur_identify_is_created);
    return true;
  }

  return false;
}

async function check_is_created_phone(
  phone: string,
  res?: Response | undefined
) {
  // 查找 身份证卡号 是否已 注册过
  let had_cur_phone = await db_user_account_identify
    .find({
      phone: phone,
    })
    .toArray();

  // 当前 电话号码 已 注册
  if (had_cur_phone.length > 0) {
    let cur_phone_is_created = new res_send_cur_phone_is_created(phone);
    res?.send(cur_phone_is_created);
    return true;
  }

  return false;
}
